package StudyCode.summary.BufferAndChannel;

import java.io.InputStream;
import java.nio.ByteBuffer;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class GetInputStreamByteBuffer {
	public static void main(String[] args) {
		ByteBuffer buf = ByteBuffer.allocate(10);
		InputStream is = newInputStream(buf);
		System.out.println("从 ByteBuffer 获取的 InputStream:");
		System.out.println(is);
	}

	private static InputStream newInputStream(final ByteBuffer buf) {
		return new InputStream() {
			public synchronized int read() {
				if (!buf.hasRemaining()) {
					return -1;
				}
				return buf.get();
			}

			public synchronized int read(byte[] bytes, int off, int len) {
				len = Math.min(len, buf.remaining());
				buf.get(bytes, off, len);
				return len;
			}
		};
	}
}
